package com.googlecode.allinclusive.fw.web.filter;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

/**
 * GZIP形式HttpResponse
 */
public class GZipHttpResponse extends HttpServletResponseWrapper {

	/*　Gzip输出流*/
	private GZipServletOutputStream gzos;
	/* Writer*/
	private PrintWriter writer;

	/**
	 * 构造方法
	 * @param response HTTP响应
	 */
	public GZipHttpResponse(HttpServletResponse response) throws IOException {
		super(response);
		gzos = new GZipServletOutputStream(response.getOutputStream());
	}

	/**
	 * 获取Gzip输出流
	 */
	@Override
	public ServletOutputStream getOutputStream() throws IOException {
		return gzos;
	}

	/**
	 * 获取PrintWriter
	 */
	@Override
	public PrintWriter getWriter() throws IOException {
		if (writer == null) {
			writer = new PrintWriter(new OutputStreamWriter(getOutputStream(),
					getCharacterEncoding()));
		}
		return writer;
	}

	public void flush() throws IOException {
		if (writer != null) {
			writer.flush();
		}
		gzos.finish();
	}
}
